define(function(require, exports){
	var $ = require("jquery");
	var pubjs    = require('pubjs');
	var view     = require('@base/view');
	var util     = require('util');
	var mediaBox = require('ads/mediaBox');
	var Drop     = require('@base/common/drop').drop;

	var Add = view.container.extend({
		init: function(config){
			config = pubjs.conf(config,{
				'class': 'uk-form P-adsAdd',
				'urlSave': 'spot/add',
				'urlSaveChannel': 'adSubChannel/add',
				'info': LANG('广告位信息'),
				// 显示标题
				'showTitle': true,
				// 显示保存、取消按钮
				'showButton': true,
				// 允许修改渠道
				'allowModifyChannel': true,
				// 编辑状态隐藏添加按钮；
				'isEdit': false,
				'media': {
					'data': null,
					'param': {
						'Type': 2
					},
					'url': 'massMedia/list',
					'id': '_id',
					'adSubChannelId': 'AdSubChannelId',
					'name': 'Name'
				},
				'view_model': {
					// 新建渠道名字
					'channelName': '',
					'showAddChannel': false,
					'eventToggleChannel': this.eventToggleChannel,
					'eventSaveChannel': this.eventSaveChannel,
					'eventHideAddChannel': this.eventHideAddChannel,
					'hasSelectChannel': false
				}
			});
			//type为2时，为代理
			this.$Type = 2;
			this.$mediaIds = 0;
			this.$mediaLists = [];
			this.$data = [];
			this.$initState = false;

			this.Super('init',arguments);
		},
		afterBuild: function(){
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			$([
				'<div class="P-adsAddContainer">',
					'<div class="M-formHead">',
						// '<span class="M-formHeadTitle">'+LANG('添加广告位')+'</span>',
					'</div>',
					'<div class="M-formCon">',
						'<div class="M-formConGroup P-adsAddChannelCon">',
							'<label class="M-formLabel group-label">'+LANG('渠道：')+'</label>',
							'<div class="group-content">',
								'<span pub-mod="ads/action/edit.channelDrop" pub-name="channel"></span>',
								'<span class="ml10" pub-name="channelTip" pub-mod="@base/tip.desc"></span>',
								'<span class="ml20 btn btn-default" ms-click="eventToggleChannel">' + LANG('新建渠道') + '</span>',
								'<div class="mt30" ms-visible="showAddChannel">',
									'<label class="mr10">' + LANG('渠道名字') + '</label>',
									'<span>',
										'<input ms-duplex-value="channelName"/>',
									'</span>',
									'<button class="btn btn-confirm ml15" ms-click="eventSaveChannel">'+ LANG('保存') + '</button>',
									'<button class="btn btn-default ml15" ms-click="eventHideAddChannel">'+ LANG('取消') + '</button>',
								'</div>',
							'</div>',
						'</div>',
						'<div ms-visible="hasSelectChannel">',
							'<div class="P-adsMediaContainer clear" pub-name="mediaBox_0" pub-mod="ads/mediaBox.main"></div>',

							'<div class="P-adsMediaContainer continueTxtBox tc clear pd20">',
								'<button class="mediaAddBtn addBtn btn btn-default-gradient">',
									'<i class="uk-icon-plus"></i>',
									LANG('继续添加媒体'),
								'</button>',
							'</div>',
						'</div>',
					'</div>',
					'<div class="M-formButtons">',
						'<span pub-name="cancel" pub-mod="@base/common/input.button" class="mr10" />',
						'<span pub-name="save" pub-mod="@base/common/input.button" />',
					'</div>',
				'</div>',
				'<div pub-name="saveNotify" pub-mod="modules/form.saveNotify"></div>'
			].join('')).appendTo(el);

			if (!c.showTitle) {
				self.find('.M-formHead').hide();
			}

			if (!c.showButton) {
				self.find('.M-formButtons').hide();
			}

			if (!c.allowModifyChannel) {
				self.find('.P-adsAddChannelCon').hide();
			}

			if (c.isEdit){
				self.find('.addBtnBox').hide();
				self.find('.continueTxtBox').hide();
			}

			var mediaAddBtn = self.find('.mediaAddBtn');
			self.uiBind(mediaAddBtn,'click',self.eventMediaAddBtn);

			var config = {
				'channel': {
					'url': 'adSubChannel/list',
					'type': 'button',
					'def': LANG('请选择渠道'),
					'width': 250,
					'panel_config': {
						'height': 200,
						'hasSearch': true,
						'def': {'name': LANG('请选择渠道')}
					}
				},
				'channelTip': {
					'data': LANG('标记广告位所用，譬如“网站联盟”可以算是一个渠道。不影响广告投放。')
				},
				'save': {
					'value': LANG('保存'),
					'class': 'btn btn-confirm mt10'
				},
				'cancel': {
					'value': LANG('取消'),
					'class': 'btn btn-link mr10 mt10'
				},
				'saveNotify': {
					'view_model': {
						'title': LANG('保存成功!'),
						'desc': LANG('您所添加的广告位已成功保存，您现在可以把它应用到代理活动中。'),
						'list_title': '',
						'buttons': [
							{name: LANG('广告位列表'), type: 'list'}
							,{name: LANG('添加广告位'), type: 'add'}
							,{name: LANG('关闭窗口'), type: 'close'}
						]
					}
				}
			};

			self.buildFromTemplate(config);

		},
		afterBuildTemplate: function(){
			var self = this;
			self.$.saveNotify.hide();
			self.loadMediaData();

			//推入默认加载的第一个media模块
			self.$mediaLists[self.$mediaIds] = self.$.mediaBox_0;
			self.$mediaIds++;

			//过滤媒体选项
			self.filterMedia(self.$.mediaBox_0);

		},
		//拉取媒体选项数据
		loadMediaData: function(){
			var self = this;
			var info = self.getConfig('media');
			pubjs.mc.send(info.url, info.param, self.onMediaData.bind(self));
		},
		//缓存媒体选项
		onMediaData: function(err, data){
			if(err){
				pubjs.error(err);
				return false;
			}
			if(!data){
				return false;
			}
			var self = this;
			var info = self.getConfig('media');

			var tmpData = [];
			for( var i = 0; i < data.items.length; i++ ) {
				if(data){
					tmpData.push({
						'id': data.items[i][info['id']],
						'adSubChannelId': data.items[i][info['adSubChannelId']],
						'name': data.items[i][info['name']]
					});
				}
			}
			self.$allMediaData = tmpData;
			self.changeMediaData();
			this.$initState = true;
		},
		changeMediaData: function()
		{
			var self = this;
			for(var i = 0; i < self.$mediaLists.length; i++)
			{
				var mod = self.$mediaLists[i];
				if (mod)
				{
					self.filterMedia(mod);
				}
			}
		},
		//响应保存和取消按键
		onInputClick: function(ev){
			switch(ev.name){
				case 'save':
					this.save();
				break;
				case 'cancel':
					pubjs.controller.navigate('ads');
				break;
			}
			return false;
		},
		//点击相应渠道下拉菜单
		onDropChange: function(ev){
			var self = this;
			for(var i=1; i<self.$mediaLists.length; i++){
				self.$mediaLists[i].destroy();

			}
			self.$mediaLists.splice(1,self.$mediaLists.length-1);
			self.$.mediaBox_0.reset();
			self.filterMedia(self.$.mediaBox_0);
			self.$mediaIds = 1;
			self.$.mediaBox_0.setChannelData(+ev.param.id);
			self.vm.$.hasSelectChannel = !!ev.param.id;
			return false;
		},
		//响应下拉输入
		onDropBlur: function(ev){
			var self = this;
			util.each(self.$mediaLists,function(mod){
				if(mod){
					self.filterMedia(mod);
					mod.reset();
				}
			});
			return false;
		},
		onMediaCloseBtn: function(ev){
			var tmpId = ev.name.split('_')[1];
			this.$mediaLists[tmpId]=null;

			return false;
		},
		//过滤和设置媒体选项
		filterMedia: function (mod){
			var self = this;
			var channelData = self.$.channel.getValue(true);

			var media = mod.$.media;
			var currentData = [];

			if(self.$allMediaData){
				util.each(self.$allMediaData,function (data){
					if(+channelData.id === data.adSubChannelId){
						if(data.name) {
							currentData.push(data);
						}
					}
				});
			}
			media.reset();
			media.setData(currentData);
		},
		//响应继续添加媒体按钮
		eventMediaAddBtn: function(){
			var self = this;
			var channelData = self.$.channel.getValue(true);
			self.$mediaIds = self.$mediaLists.length;
			self.$mediaLists[self.$mediaIds] = self.create(
				'mediaBox_'+self.$mediaIds,
				mediaBox.main,
				{
					'target': self.find('.M-formContent'),
					'class':"P-adsMediaContainer clear",
					'closeBtn': true
				}
			);
			self.$mediaLists[self.$mediaIds].setChannelData(+channelData.id);
			self.find('.continueTxtBox').before(self.$mediaLists[self.$mediaIds].$el);

			self.filterMedia(self.$mediaLists[self.$mediaIds]);
			self.$mediaIds++;
			return false;
		},
		setTitle: function(text){
			var el = this.getDOM();
			if(text){
				el.find('.M-formHeadTitle').text(text);
			}
			return this;
		},
		getData: function(){
			var self = this;
			var data;
			var mediaBoxTmp = [];
			for(var i =0;i<self.$mediaLists.length;i++){
				if(self.$mediaLists[i]){
					mediaBoxTmp = mediaBoxTmp.concat(self.$mediaLists[i].getData());
				}
			}
			var channel = this.$.channel.getValue(true);
			//监测活动的时候，新建的渠道数据,导致渠道数据需要更新
			//但是如果采用更新渠道数据的方式话，可能在数据update回来前就点击保存广告位，导致取不到新增的渠道数据
			//现在直接使用缓存的渠道数据。
			if (self.$IsMonitorCampaign && self.$ChannelId && self.$AdSubChannelName)
			{
				channel = {
					id: self.$ChannelId,
					name: self.$AdSubChannelName
				};
			}

			data = {
				Type: self.$Type,
				ChannelId: channel.id || 0,
				AdSubChannelId: channel.id,
				AdSubChannelName: channel.name,
				AdPositions: mediaBoxTmp
			}
			return data;
		},
		setData: function(data){
			var self = this;
			self.$ChannelId = data.ChannelId;
			self.$AdSubChannelName = data.AdSubChannelName;
			self.$IsMonitorCampaign = true;

			//检测活动里添加广告位的话，需要注意先更新渠道数据。
			if (data.ChannelId && data.AdSubChannelName) {
				self.$.channel.setValue(data.ChannelId);
				self.$.channel.load().setValue(data.ChannelId);

				util.each(self.$mediaLists,function(mod){
					if(mod){
						self.filterMedia(mod);
						mod.reset();
					}
				});
			}
		},
		reset: function(data){
			var self = this;
			self.$data = [];
			self.$mediaIds = 0;
			self.$.channel.reset();
			for(var i=1;i<self.$mediaLists.length;i++){
				if(self.$mediaLists[i]){
					self.$mediaLists[i].destroy();
				}
			}
			self.$mediaLists[0].reset();
			self.$mediaLists.splice(1,self.$mediaLists.length-1);
			self.filterMedia(self.$mediaLists[0]);
			self.find('.P-adsAdd').show();
			self.$.saveNotify.hide();

			//重置新建监测活动时的相关数据
			self.$ChannelId = 0;
			self.$AdSubChannelName = null;
			self.$IsMonitorCampaign = false;

			return self;
		},
		validate: function(data) {
			var dataValidate = true;
			data = data || this.getData();
			//判断渠道名字和媒体名字是否为空
			if(!data.AdSubChannelName){
				pubjs.alert('渠道名字不能为空');
				dataValidate = false;
				return false;
			}
			util.each(data.AdPositions,function(data){
				if(!data.MediaName){
					pubjs.alert('媒体名字不能为空');
					dataValidate = false;
					return false;
				}
				if(data.SystemDeduct && !data.Cost) {
					pubjs.alert('成本价不能为空');
					dataValidate = false;
					return false;
				}
			});
			return dataValidate;
		},
		save: function(){
			if (!this.$initState)
			{
				pubjs.alert('数据未完成返回，请稍后进行保存操作');
				return false;
			}

			var self = this;
			var data = self.getData();
			var url = self.getConfig('urlSave');
			if (this.validate()) {
				self.showLoading();
				pubjs.mc.send(url,data,self.onSave.bind(self));
			}
		},
		onSave: function(err, data){
			var c = this.getConfig();
			this.hideLoading();
			if(err){
				pubjs.alert(err.message);
				return false;
			}else{

				if (!c.showButton) {
					this.fire('saveSuccess', {data: data.items});
				} else {
					// this.$data = data.items;
					this.find('.P-adsAddContainer').hide();
					if(data.items && data.items[0]){
						var item = data.items[0];
						var title = '【' + item._id + '】' + item.Name;
						this.$.saveNotify.setContentTitle(LANG('广告位名称：')+ title);
					}
					this.$.saveNotify.show();
				}
			}
			//保存后的返回操作
			return false;
		},
		onSaveNotifyOperate: function(ev){
			this.$.saveNotify.hide();
			switch (ev.param.type){
				case 'close':
					pubjs.controller.navigate('ads');
					break;
				case 'add':
					this.reset();
					pubjs.controller.navigate('ads/add');
					break;
				case 'list':
					pubjs.controller.navigate('ads');
					break;
			}
			this.$.saveNotify.hide();
			return false;
		},
		eventToggleChannel: function()
		{
			var vm = this.vm.$;
			vm.showAddChannel = !vm.showAddChannel;
		},
		eventSaveChannel: function()
		{
			var self = this;
			var vm = self.vm.$;
			var name = vm.channelName;
			var url = self.getConfig('urlSaveChannel');

			if (!name)
			{
				pubjs.alert(LANG('请输入渠道名称'));
				return false;
			}

			pubjs.mc.send(url, {'Name': name}, function(err, data){
				if (err)
				{
					pubjs.alert(err.message);
					return false;
				}
				// 隐藏添加渠道模块
				self.eventHideAddChannel();
				// 更新渠道下拉菜单的数据
				self.$.channel.load();
			});
		},
		eventHideAddChannel: function()
		{
			var vm = this.vm.$;
			vm.showAddChannel = false;
			vm.channelName = '';
		},
		onUpateMediaData: function()
		{
			this.loadMediaData();
			// return false;
		},
		onSetChannelId: function(ev){
			this.getConfig().media.param.ChannelId = +ev.param;
		}
	});
	exports.add = Add;

	var Edit = Add.extend({
		init: function(config){
			config = pubjs.conf(config,{
				'urlInfo': 'spot/info',
				'urlUpdate': 'spot/update',
				// 'adId': '',  //要编辑的广告位id
				//'adId': '57',  //todo 暂时以固定id不编辑
				'info': LANG('广告位信息'),
				'showButton': true,
				'isEdit': true
			});
			this.$Type = 2;
			this.$mediaIds = 0;
			this.$mediaLists = [];
			this.$data = null;
			this.$adId = 0;
			this.Super('init',arguments);
		},
		afterBuildTemplate: function(){
			var self = this;
			self.$.saveNotify.hide();
			self.find('.addBtnBox').hide();
			self.find('.continueTxtBox').hide();
			// self.load();
			//过滤媒体选项
			self.filterMedia(self.$.mediaBox_0);

		},
		//暂时只是加载媒体选项的list
		load: function(id){
			var self = this;
			pubjs.loading.show();
			if(id){
				var c = self.getConfig();
				// var info = self.getConfig('media');
				this.$adId = +id;
				var param = {
					'_id': +id //加载要编辑的广告位
				};
				pubjs.mc.send(c.urlInfo,param,self.onData.bind(self));
			}
		},
		onData: function(err,data){
			if(err){
				pubjs.error(err);
				pubjs.alert(err.message);
				pubjs.controller.navigate('ads');
				return false;
			}
			if(!data){
				pubjs.controller.navigate('ads');
				return false;
			}
			this.setData(data);
			this.loadMediaData();
		},
		//设置缓存媒体选项
		onMediaData: function(err,data){
			if(err){
				pubjs.error(err);
				return false;
			}
			if(!data){
				return false;
			}
			var self = this;
			var info = self.getConfig('media');

			var tmpData = [];
			for( var i = 0; i < data.items.length; i++ ) {
				if(data){
					tmpData.push({
						'id': data.items[i][info['id']],
						'adSubChannelId': data.items[i][info['adSubChannelId']],
						'name': data.items[i][info['name']]
					});
				}
			}
			self.$allMediaData = tmpData;
			self.filterMedia(self.$.mediaBox_0);
			// 媒体拉取完毕，更新值
			if(self.$data){
				self.$.mediaBox_0.setData([self.$data]);
			}

			this.$initState = true;
			pubjs.loading.hide();
		},
		//点击相应渠道下拉菜单
		onDropItemSelected: function (ev){
			var self = this;

			self.$.mediaBox_0.reset();
			self.filterMedia(self.$.mediaBox_0);
			self.$mediaIds = 1;
			return false;
		},
		//提取广告位数据
		getData: function(){
			return {
				_id: this.$adId,
				Type: this.$Type,
				ChannelId: this.$.channel.getValue(true).id || 0,
				AdPositions: this.$.mediaBox_0.getData(),
				AdSubChannelId: this.$.channel.getValue(true).id,
				AdSubChannelName: this.$.channel.getValue(true).name
			}
		},
		setData: function(data){
			this.$data = data;
			this.$ChannelId = data.ChannelId;
			this.$.channel.setValue(data.AdSubChannelId);
			this.vm.$.hasSelectChannel = !!data.AdSubChannelId;
			return this;
		},
		reset: function(data){
			this.$.mediaBox_0.reset();
			this.find('.P-adsAdd').show();
			this.filterMedia(this.$.mediaBox_0);
			this.$data = null;
			return this;
		},
		save: function(){
			if (!this.$initState)
			{
				pubjs.alert('数据未完成返回，请稍后进行保存操作');
				return false;
			}


			var self = this;
			var data = self.getData();
			var url = self.getConfig('urlUpdate');
			//判断渠道名字和媒体名字是否为空
			var dataValidate = true;
			if(!data.AdSubChannelName){
					pubjs.alert('渠道名字不能为空');
					dataValidate = false;
					return false;
			}
			util.each(data.AdPositions,function(data){

				if(!data.MediaName){
					pubjs.alert('媒体名字不能为空');
					dataValidate = false;
					return false;
				}
				if(data.SystemDeduct && !data.Cost) {
					pubjs.alert('成本价不能为空');
					dataValidate = false;
					return false;
				}
			});
			if(dataValidate){
				self.showLoading();
				pubjs.mc.send(url,data,self.onSave.bind(self));
			}
		}
	});
	exports.edit = Edit;


	// 暂时处理drop的异步数据问题。
	var ChannelDrop = Drop.extend({
		setValue: function(value)
		{
			this.Super('setValue', arguments);
			// this.$panel.setValue(value);
			this.$tmpValue = value;
			return this;
		},
		setData: function()
		{
			this.Super('setData', arguments);
			if (this.$tmpValue)
			{
				this.setValue(this.$tmpValue);
			}
			return this;
		},
		reset: function()
		{
			this.Super('reset', arguments);
			this.$tmpValue = null;
			return this;
		}
	});
	exports.channelDrop = ChannelDrop;
});